package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"github.com/dgrijalva/jwt-go"
	"gomuisc/models/mysql"
	"gomuisc/service"
)
type MyClaims struct {
	Username string `json:"username"`
	Id int `json:"id"`
	jwt.StandardClaims
}
func Register(c *gin.Context)  {
	name,ok := c.GetPostForm("name")
	if !ok {
		c.JSON(http.StatusOK,gin.H{
			"code":201,
			"message":"账号不能为空",
		})
		return
	}
	pwd,ok := c.GetPostForm("pwd")
	if !ok{
		c.JSON(http.StatusOK,gin.H{
			"code":201,
			"message":"账号不能为空",
		})
		return
	}
	pwds,ok := c.GetPostForm("pwds")
	if !ok{
		c.JSON(http.StatusOK,gin.H{
			"code":201,
			"message":"账号不能为空",
		})
		return
	}
	fmt.Println(name)
	fmt.Println(pwd)
	fmt.Println(pwds)
	if(pwd != pwds){
		c.JSON(http.StatusOK,gin.H{
			"code":201,
			"message":"两次密码不一致",
		})
		return
	}

	mysqlSink,err := mysql.NewMysqlSink()
	if err != nil{
		return
	}
	defer mysqlSink.Close()

	rows,err :=  mysqlSink.GetUser(name);
	if err != nil{
		c.JSON(http.StatusOK,gin.H{
			"code":201,
			"message":"异常错误",
		})
		return
	}
	if len(rows) == 0 {
		_,err := mysqlSink.InsertUser(mysql.User{
			Username:name,
			Password:pwd,
			Salt:service.GenerateSubId(6),
		})
		if err != nil{
			c.JSON(http.StatusOK,gin.H{
				"code":201,
				"message":"注册失败",
			})
			return
		}
		c.JSON(http.StatusOK,gin.H{
			"code":200,
			"message":"注册成功",
		})
		return
	}
	c.JSON(http.StatusOK,gin.H{
		"code":201,
		"message":"该账号已被注册",
	})
	return

}
func Login(c *gin.Context)  {
	var user mysql.User
	err := c.ShouldBind(&user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 2001,
			"msg":  "无效的参数",
		})
		return
	}
	fmt.Println("接收到的数据", user)
	mysqlSink,err := mysql.NewMysqlSink()
	if err != nil{
		return
	}
	defer mysqlSink.Close()


	row,err := mysqlSink.GetUser(user.Username)
	if err != nil{
		return
	}
	if len(row) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 201,
			"msg":  "找不到该用户",
		})
		return
	}

	// 校验用户名和密码是否正确
	if user.Password == row[0].Password {
		// 生成Token
		tokenString, _ := GenToken(user.Username,row[0].Id)
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "success",
			"data": gin.H{"token": tokenString},
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 202,
		"msg":  "鉴权失败",
	})
	return
}
// GenToken 生成JWT

// ParseToken 解析JWT
// 根据用户的用户名和密码产生token
